package converter;

import java.util.List;

import metier.ContexteComposant;
import metier.ModeleClasse;
import metier.ModeleTaille;
import noNamespace.EcranDocument.Ecran.Composants.TextComposant;
import noNamespace.EcranDocument.Ecran.Composants.TextComposant.Composant;
import noNamespace.EcranDocument.Ecran.Composants.TextComposant.ModeleClass;

import org.apache.commons.lang.StringUtils;

public class ComposantConverter {

	public static ContexteComposant getContexte(TextComposant aTextComposant,Composant aComposant){
		ContexteComposant lContexteComposant = new ContexteComposant();
		lContexteComposant.setAction(aComposant.getAction());
		lContexteComposant.setActiver(aComposant.getActiver());
		lContexteComposant.setBean(aComposant.getBean());
		lContexteComposant.setCp1(aComposant.getCp1());
		lContexteComposant.setCp2(aComposant.getCp2());
		lContexteComposant.setDefaut(aComposant.getDefaut());
		if(convertible(aComposant.getHeight())){
		lContexteComposant.setHeight(Integer.parseInt(aComposant.getHeight()));
		}
		if(convertible(aComposant.getWidth())){
		lContexteComposant.setWidth(Integer.parseInt(aComposant.getWidth()));
		}
		lContexteComposant.setModeleClasse(getModeleClasse(aTextComposant.getModeleClassList(),aComposant.getModeleClasse()));
		lContexteComposant.setModeleTaille(getModeleTaille(aTextComposant.getModeleTailleList(),aComposant.getModeleTaille()));
		lContexteComposant.setNom(aComposant.getNom());
		lContexteComposant.setTitre(aComposant.getTitre());
		lContexteComposant.setX(aComposant.getX());
		lContexteComposant.setY(aComposant.getY());
				
		return lContexteComposant;
	}

	private static ModeleTaille getModeleTaille(List<noNamespace.EcranDocument.Ecran.Composants.TextComposant.ModeleTaille> aList, String aModeleTaille) {
		try {
			for (noNamespace.EcranDocument.Ecran.Composants.TextComposant.ModeleTaille lModele : aList) {
				int lId = lModele.getId();
				int lIdModele = Integer.parseInt(aModeleTaille);
				if (lId == lIdModele) {
					int lWidth = lModele.getWidth();
					int lHeight = lModele.getHeight();
					return new ModeleTaille(lHeight, lWidth);
				}
			}
		} catch (NumberFormatException e) {
			return null;
		}
		return null;
	}

	private static ModeleClasse getModeleClasse(List<ModeleClass> aList, int aModeleClasse) {
		for (ModeleClass lModele : aList) {
			int lId = lModele.getId();
			if (lId == aModeleClasse) {
				String lClasse = lModele.getClasse();
				return new ModeleClasse(lClasse);
			}
		}
		return null;
	}
	
	private static boolean convertible(String aChaine){
		if(aChaine == null){
			return false;
		}
		if (StringUtils.isBlank(aChaine)){
			return false;
		}
		if(StringUtils.isEmpty(aChaine)){
			return false;
		}
		
		return true;
	}
}
